package com.wzy.cglibProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ProxyFactory implements MethodInterceptor {

    private IUserDao target;

    public IUserDao getInstance(IUserDao target){
        this.target = target;  //给代理对象赋值
        Enhancer enhancer = new Enhancer(); //创建加强器，用来创建动态代理类
        enhancer.setSuperclass(this.target.getClass());//为加强器指定要代理的业务类（即：为下面生成的代理类指定父类）
        //设置回调：对于代理类上所有方法的调用，都会调用CallBack，而Callback则需要实现intercept()方法进行拦截
        enhancer.setCallback(this);
        // 创建动态代理类对象并返回
        IUserDao $proxy = (IUserDao) enhancer.create();
        return $proxy;
    }

    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        beginTransaction();
        Object returnValue = methodProxy.invokeSuper(obj,args);
        endTransaction();
        return returnValue;
    }

    private void beginTransaction(){
        System.out.println("开始事务...");
    }

    private void endTransaction(){
        System.out.println("结束事务...");
    }
}
